<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-10-06 15:42:32
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\ProOutsourcingDelivery;

class ProOutsourcingDeliveryRepository extends Repositories
    {
    public $relation_models = ['raws' => ['material', 'storage'], 'outfactory', 'car' => ['company'], 'details' => ['material', 'outfactory', 'creator', 'updator', 'location', 'packs' => ['material']], 'process_route', 'processes' => ['process']];
    public function boot(ProOutsourcingDelivery $model)
        {
        $this->model = $model;
        }

    public function audit($model)
        {
        $deltails = $model->details;
        $raws     = $model->raws;
        if ($model->status_id != 0) {
            fail("单据状态{$model->status->name},操作失败！");
            }
        $deltails->filter(function ($v)
            {
            $v->packs->filter(function ($vv) use ($v)
                {
                $vv->useStorage("外发出库");
                $vv->subStorage();
                $newlocation_id = $v->outfactory->getLocation(1);
                //新增库存,保存汇总库存ID
                $vv->summary_storage_id = $vv->mergeWhere(['location_id' => $newlocation_id])
                    ->addStorage("委外入库", $vv->code, 0, 0, "new_mpc_detail")->summary_storage_id;

                });
            auditSave($v);
            });
        $raws?->filter(function ($vv) use ($model)
            {
            $vv->useStorage("外发出库");
            $vv->subStorage();
            $newlocation_id = $model->outfactory->getLocation(1);
            //新增库存,保存汇总库存ID
            $vv->summary_storage_id = $vv->mergeWhere(['location_id' => $newlocation_id])
                ->addStorage("委外入库", null, 0, 0, "new_mpc_detail")->summary_storage_id;
            $vv->save();
            });
        auditSave($model);
        }

    public function noaudit($model)
        {
        if ($model->status_id != 1) {
            fail("单据状态{$model->status->name},操作失败！");
            }
        $deltails = $model->details;
        $raws     = $model->raws;

        $deltails->filter(function ($v)
            {
            $v->packs->filter(function ($vv)
                {
                $vv->nosubStorage();
                $vv->nouseStorage();
                $vv->noaddStorage("new_mpc_detail");
                });
            auditSave($v, false);
            });
        $raws?->filter(function ($v)
            {
            $v->nosubStorage();
            $v->nouseStorage();
            $v->noaddStorage("new_mpc_detail");
            });
        auditSave($model, false);
        }
    }